package cn.wolfcode.crm.web.controller;


import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.PermissionService;
import cn.wolfcode.crm.service.RoleService;
import cn.wolfcode.crm.utils.JsonResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model , @ModelAttribute("qo" )QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "/role/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                roleService.deleteByPrimaryKey(id);
            }
        }catch (Exception e){
            return new JsonResult(false ,"删除失败");
        }

        return new JsonResult(true ,"删除成功");

    }
    @RequestMapping("/input")
    public String input(Model model,Long id) {
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions",permissions);
        if (id != null) {
            Role role = roleService.selectByPrimaryKey(id);
            model.addAttribute("role",role);
        }
        return "/role/input";

    }
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Role role, Long[] permissionIds) {
       try {
           if(role.getId()!=null) {
               roleService.updateByPrimaryKey(role,permissionIds);
           }else {
               roleService.insert(role,permissionIds);
           }
       }catch (Exception e){

           return new JsonResult(false ,"保存添加失败");
       }

        return new JsonResult(true ,"保存添加成功");



    }


}
